package com.ocean.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {

    public static void main(String[] args) {
        int[] src = new int[]{0, 0, 0};
        List<List<Integer>> result = new ThreeSum().threeSum(src);
        System.out.println(result);
    }

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums.length < 3) {
            return result;
        }
        Arrays.sort(nums);
        for (int first = 0; first < nums.length; first++) {
            if (nums[first] > 0) {
                return result;
            }
            // 跳过相同的元素
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            // 创建两个指针

            int right = nums.length - 1;
            int left = first + 1;
            while (left < right) {
                int sum = nums[first] + nums[left] + nums[right];
                if (sum == 0) {
                    List<Integer> find = new ArrayList<>();
                    find.add(nums[first]);
                    find.add(nums[left]);
                    find.add(nums[right]);
                    result.add(find);
                    while (left < right && nums[left] == nums[left + 1]) {
                        //跳过重复的
                        left++;
                    }
                    while (left < right && nums[right] == nums[right - 1]) {
                        //跳过重复的
                        right--;
                    }
                    left++;
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }

        }
        return result;
    }
}
